import sys
import os
import pylab as plt
from params import *

fig_width_pt = 246.0  # Get this from LaTeX using \showthe\columnwidth
inches_per_pt = 1.0/72.27               # Convert pt to inch
golden_mean = (sqrt(5)-1.0)/2.0         # Aesthetic ratio
fig_width = fig_width_pt*inches_per_pt  # width in inches
fig_height = fig_width*golden_mean      # height in inches
fig_size =  [fig_width,fig_height]
params = {'backend': 'ps',
        'axes.labelsize': 12,
        'text.fontsize': 10,
        'legend.fontsize': 10,
        'xtick.labelsize': 12,
        'ytick.labelsize': 12,
        'lines.markersize': 3,  
        'lines.mfc': 'g',  
        'text.usetex': True,
        'figure.figsize': fig_size}
pylab.rcParams.update(params)

def avg(seq):
    if not seq:
        return 0.0
    else:
        return float(sum(seq))/len(seq)

def std(seq):
    if not seq:
        return 0.0
    else:
        a = avg(seq)
        var = float(sum((i - a)**2 for i in seq)) / len(seq)
        return var**0.5

DIR = os.path.join(WORKDIR, 'gsn', 'cpp', 'limelight', 'results')
DIR = os.path.join(WORKDIR, 'gsn', 'cpp', 'limelight', 'results_new')
def extract_params(filename):
    try:
        params = filename[:-4].split('_')
        cache, weight,size = map(int,params[2:5])
        traffic_prob = float(params[5])
        retweet = float(params[6])
        r = {}
        r['cache_mode'] = cache
        r['weight_mode'] = weight
        r['cache_size'] = size
        r['traffic_ratio'] = traffic_prob
        r['retweet'] = retweet

        return r
    except:
        return None

data = {}
for file in os.listdir(DIR):
    params = extract_params(file)
    if not params:
        continue
    cache_mode = params['cache_mode']
    weight_mode = params['weight_mode']
    retweet_ratio = params['retweet']
    size = params['cache_size']
    #if size > 100:
    #    continue

    if retweet_ratio == 0:
        continue
    if retweet_ratio > 0.005:
        continue
    if not cache_mode in data:
        data[cache_mode] = {}
    t = data[cache_mode]
    if not weight_mode in t:
        t[weight_mode] = {}
    t = t[weight_mode]
    if not retweet_ratio in t:
        t[retweet_ratio] = {}
    t = t[retweet_ratio]
    if not size in t:
        t[size] = []
    t = t[size]

    total_hits = 0
    total_misses = 0
    total_cold = 0
    first = True
    for line in open(os.path.join(DIR,file)):
        if first:
            first = False
            num_req, num_videos = map(int,line.split(';'))
            continue

        server,name,hits,misses,cold_misses = line.split(';')
        h,m,c = map(int,(hits,misses,cold_misses))
        total_hits += h
        total_misses += m
        total_cold += c
        if m:
            hit_ratio = 1.0*h/(h+m-c)
        else:
            hit_ratio = 0
        print 'Server %s hit ratio %f'%(name,hit_ratio)
    #gain on infinite cache
    total_hit_ratio = 1.0*total_hits/(total_hits+total_misses-total_cold)
    t.append(total_hit_ratio)

for cache_mode in sorted(data):
    for weight_mode in sorted(data[cache_mode]):
        print cache_mode, weight_mode
        t = data[cache_mode][weight_mode]
        #markers = list('xv.+sd*')
        ax = plt.figure()
        plt.clf()
        plt.axes(FIG_AXES2)
        lbl = []
        patches = []
        for retweet,marker,color in zip(sorted(t),markers,colors):
            x,y,y2, y3 = [],[], [], []
            for size in sorted(t[retweet]):
                #x.append(1.0*size/1000000)
                x.append(size)
                print len(t[retweet][size])
                y.append(100*avg(t[retweet][size]))
                err = 100*std(t[retweet][size])
                print y[-1], err
                y2.append(y[-1] - 3 * err)
                y3.append(y[-1] + 3 * err)
#                print 'Cache size %d: hit ratio %f'%(x[-1],y[-1])
            p = plt.plot(x,y,'%s%s-'%(color,marker), markersize=5, mec=color, mfc='None')
            #plt.plot(x,y2,'k%s:'%marker, markersize=5, mfc='None')
            #plt.plot(x,y3,'k%s:'%marker, markersize=5, mfc='None')
            lbl.append('p = %.3f'%retweet)
            patches.append(p[0])

        plt.xlabel('Cache size [\%]')
        plt.ylabel('Optimal hits [\%]')
        plt.grid(True)
        plt.legend(patches, lbl,loc='lower right',ncol=2,
                numpoints=1,markerscale=1.00,
                handletextpad=0.10,
                borderpad=0.15,
                columnspacing=0.10)

        if cache_mode == 0:
            cache_name = 'LRU'
        elif cache_mode == 1:
            cache_name = 'LFU'
        else:
            cache_name = 'MIXED'

        if weight_mode == 0:
            weight_name = 'No weight'
        elif weight_mode == 1:
            weight_name = 'Geosocial'
        else:
            weight_name = 'Geocascade'

#        if cache_mode == 0:
#            print 'write weight mode ', weight_name
#            plt.text(500, 114, weight_name,
#                    ha='center',va='center',
#                    bbox=dict(facecolor='white'))
#        if weight_mode == 2:
#            print 'write cache mode ', cache_name
#            plt.text(1080, 50, '\n'.join(cache_name),
#                    ha='center',va='center',
#                    bbox=dict(facecolor='white'))

        title_name = '%s - %s'%(cache_name,weight_name)
        [x0,x1,y0,y1] = plt.axis()
        loc,labels = plt.xticks()
        new_labels = map(lambda x: '$%.2f$'%(float(100*x)/1e6),loc)
        plt.xticks(loc,new_labels)

        plt.axis([x0,x1,0,100.0])
        #plt.title(title_name)
        plt.savefig('cache_hits_%d_%d.pdf'%(
            cache_mode,weight_mode))
        plt.close()

